﻿using Dapper.DBContext;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Extension;
using Guoc.BigMall.WebService.Dto;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guoc.BigMall.WebService.Implement
{
    public class ProductService : IProductServce
    {
        IDBContext _db;
        public ProductService(IDBContext dbContext)
        {
            this._db = dbContext;

        }

        public ProductVo GetByCode(string productCode)
        {
            var sql = @"select p.Id as ProductId,p.Code as ProductCode,p.showName,p.SellingPoint,p.Specification,p.OldPrice,p.SalePrice
from Product p where p.Code = @ProductCode ";

            var product = _db.DataBase.QuerySingle<ProductVo>(sql, new { ProductCode = productCode });

            if (product == null)
                throw new FriendlyException("商品:{0} 不存在".FormatWith(productCode));

            // 商品图片
            var sqlPic = @"select Id,ImageUrl from ProductPicture where ProductId =@ProductId order by `Order` ";
            var pictures = _db.DataBase.Query<ProductPictureVo>(sqlPic, new { ProductId = product.ProductId }).ToList();
            product.Pictures = pictures;
            return product;
        }

        public ProductVo GetById(int productId)
        {
            var sql = @"select p.Id as ProductId,p.Code as ProductCode,p.showName,p.SellingPoint,p.Specification,p.OldPrice,p.SalePrice
from Product p where p.Id = @ProductId ";

            var product = _db.DataBase.QuerySingle<ProductVo>(sql, new { ProductId = productId });

            if (product == null)
                throw new FriendlyException("商品:{0} 不存在".FormatWith(productId));
            return product;
        }

        public IEnumerable<ProductVo> GetProductList(PageVo page)
        {
            IEnumerable<ProductVo> rows;
            dynamic param = new ExpandoObject();
            string where = "";

            where += " and p.Status =@Status";
            param.Status = (int)ProductStatus.OnSale;

            string sql = @" SELECT p.Id as ProductId,p.Code as ProductCode,p.ShowName,p.SellingPoint,p.Specification,p.OldPrice,p.SalePrice,pp.ImageUrl 
FROM   Product p left join ProductPicture pp on p.Id = pp.ProductId 
                                WHERE 1=1 {0} Order By  p.Id desc LIMIT {1},{2}";
            sql = string.Format(sql, where, (page.PageIndex - 1) * page.PageSize, page.PageSize);
            rows = _db.DataBase.Query<ProductVo>(sql, param);           
            return rows;
        }
    }
}
